Ext.define('App.SecurityApplication', {
    extend: 'Ext.app.Application',
    name: 'App',
    constructor: function () {
        var that = this;
        Ext.Ajax.on({
            beforerequest: that.onBeforeRequest,
            requestexception: that.onRequestException,
            requestcomplete: that.onRequestComplete,
            scope: that
        });
        this.callParent(arguments);
    },
    onBeforeRequest: function (conn, operation, eOpts) {
        if (Ext.isEmpty(operation.url)) {
            Extend.Msg.error('错误', '没有提供URL无法完成操作请求，请修改请求参数后重试！')
            Ext.log({
                level: 'error',
                msg: '没有提供URL无法完成操作请求，请修改请求参数后重试！',
                dump: operation
            });
            conn.abort();
            return false;
        }
        if (!Ext.isEmpty(operation.params) && !Ext.isEmpty(operation.params['pageable.page'])) {
            operation.params['pageable.page'] = operation.params['pageable.page'] - 1;
        }
        // 配置全局请求参数
        Ext.apply(operation, {
            //设置请求超时时间为2分钟
            timeout: (operation.timeout <= 120 * 1000) ? 120 * 1000 : operation.timeout,
            method: operation.method || "POST",
            url: operation.url.replace(/_dc=/, 'dc='),
            defaultHeaders: {
                'request_type': 'ajax'
            }
        })
        Ext.log({
            level: 'info',
            msg: 'Request:' + operation.url,
            dump: operation
        });
    },
    onRequestException: function (conn, resp, options, eOpts) {
        var that = this;
        Ext.log({
            level: 'error',
            msg: 'Response:' + options.url,
            dump: resp
        });

        var status = resp.status;

        //将Response数据转换成JSON
        resp.result = that.responseTextToJson(resp.responseText);

        //创建错误消息详细信息（debug模式下才创建）
        var errors = null;


        var exception = null;
        if (window.isDebug == true) {
            errors = that.createErrors(resp, options);
            if (!Ext.isEmpty(resp.result.exception)) {
                exception = resp.result.exception;
            }
        }
        if (status === 0 && resp.timedout === true) {
            var error = '请求超时：' + options.url;
            Extend.Msg.error('错误(status=' + status + ')', error);
        } else if (status === 401 || status == 403) {
            that.pushRequestOption(options);
            var error = resp.result.result || (status == 401 ? "资源请求失败，请求的资源需要在您登录后才能访问！" : "资源请求失败，当前用户没有取得该资源的授权，请联系管理员授权！");
            var cfg = {
                title: '错误(' + (resp.result.statusText || resp.result.status) + ')',
                icon: Extend.Msg.ERROR,
                message: error,
                buttons: Extend.Msg.OK,
                callback: function (opt) {
                    if (resp.result.status == 401.1 && Ext.isFunction(that.showLoginWindow)) {
                        that.showLoginWindow();
                    }
                }
            }
            Extend.Msg.show(cfg);
        } else if (status === 404) {
            var error = resp.result.result || "资源请求失败，请求的资源不存在或已经移除！";
            Extend.Msg.error('错误(status=' + status + ')', error, null, errors, exception);
        } else if (status === 500) {
            var error = resp.result.result || '资源请求失败，请求的资源发生异常！';
            Extend.Msg.error('错误(status=' + status + ')', error, null, errors, exception);
        } else {
            var error = resp.result.result || '资源请求发生错误:' + options.url;
            Extend.Msg.error('错误(status=' + status + ')', error, null, errors, exception);
        }
    },
    onRequestComplete: function (conn, resp, options, eOpts) {
        Ext.log({
            level: 'info',
            msg: 'Response:' + options.url,
            dump: resp
        });
        // 取得此次请求的url地址
        var url = this.getFullUrl(options.url);
        var text = Ext.String.trim(resp.responseText);

        // 将结果转换为JSON格式，如果异常则报错
        try {
            resp.result = Ext.decode(text);
        } catch (e) {
            if (text.indexOf("用户名") > -1) {
                resp.responseText = "{success:true,result:'用户未登录或超时退出，请重新登录后重试！'}";
                this.showLoginWindow();
            } else {
                var error = '返回数据不是合法的JSON格式!';
                Extend.Msg.error('错误', error, {
                    '返回数据': text
                });
            }
            return;
        }
        if (!Ext.isEmpty(resp.result)) {
            var error = resp.result.result
                ? resp.result.result
                : (resp.result.exception
                    ? '资源请求失败，请求的资源出现异常！'
                    : '资源请求失败！');
            if (resp.result.success === false) {
                if (isDebug) {
                    //有结果描述就使用结果描述，如果没有，则看是否存在异常，如果存在则报异常错误，否则报业务处理失败的错误
                    Extend.Msg.error("错误", error,
                        resp.result.messages,
                        resp.result.errors,
                        resp.result.exception);
                } else {
                    Extend.Msg.error("错误", error,
                        resp.result.messages,
                        resp.result.errors);
                }
                return;
            } else {
                if (!Ext.isEmpty(resp.result.errors)) {
                    Extend.Msg.error("错误", error,
                        resp.result.messages,
                        resp.result.errors);
                }
            }

        }
    },
    getFullUrl: function (url) {
        if (!Ext.String.startsWith(url, 'http')) {
            var host = window.location.origin;
            if (!Ext.String.startsWith(url, "/")) {
                host = window.location.href.substring(0,
                    window.location.href.lastIndexOf('/') + 1);
            }
            url = host + url;
        }
        return url;
    },
    responseTextToJson: function (responseText) {
        try {
            if (!Ext.isEmpty(responseText)) {
                var result = Ext.decode(responseText);
                return result;
            } else {
                Ext.log({
                    level: 'error',
                    msg: '解析错误，请求地址返回数据为空!'
                });
            }
        } catch (e) {
            Ext.log({
                level: 'error',
                msg: '解析错误，请求地址返回数据不是JSON格式!'
            });
        }
        return {};
    },
    createErrors: function (resp, options) {
        var that = this;
        var errors = null;
        if (!Ext.isEmpty(resp.result)) {
            errors = {
                'url': that.getFullUrl(options.url),
                "status": resp.result.status,
                "statusText": resp.result.statusText || resp.result.error
            };
            if (!Ext.isEmpty(resp.result.result)) {
                errors['result'] = resp.result.result;
            }
            if (!Ext.isEmpty(resp.result.failureType)) {
                errors['failureType'] = resp.result.failureType;
            }
        } else {
            errors = {
                "status": resp.status,
                "statusText": resp.statusText
            };
            if (!Ext.isEmpty(resp.responseText)) {
                errors['responseText'] = resp.responseText;
            }
        }
        return errors;
    },
    pushRequestOption: function (options) {
        if (Ext.isEmpty(window.requestQueue)) {
            window.requestQueue = new Ext.util.MixedCollection();
        }
        window.requestQueue.add(Ext.id(), options);
    },
    executeRequestQueue: function () {
        for (var i = 0; i < window.requestQueue.getCount(); i++) {
            var opts = window.requestQueue.removeAt(i);
            try {
                if (opts.defaultHeaders.request_type === 'ajax') {
                    if (Ext.isEmpty(opts.scope)) {
                        Ext.Ajax.request(opts);
                    } else if (opts.scope instanceof Ext.form.action.Action) {
                        Ext.Ajax.request(opts);
                    }
                    else if (opts.scope instanceof
                        Ext.data.proxy.Proxy) {
                        opts.operation.config.scope.reload();
                    }
                }

            } catch (e) {
            }
        }
    }
})